import 'dart:math';

import 'package:flukit/flukit.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_share/flutter_share.dart';
import 'package:hello_flutter/domain/AppData.dart';
import 'package:hello_flutter/util/utils.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

class ProfilePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _ProfilePageState();
  }
}

class _ProfilePageState extends State<ProfilePage> {
  @override
  void initState() {
    super.initState();
  }

  Future<AppData> refresh() {
    var appdata = Provider.of<AppData>(context, listen: false);
    if (appdata.userPAT != '') appdata.refresh();
    return Future.value(appdata);
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<AppData>(
      future: refresh(),
      builder: (context, data) {
        return Scaffold(
          body: PullRefreshWithScrollView(),
          floatingActionButton: FloatingActionButton(
            onPressed: () =>
                FlutterShare.share(
                    title: '周报', text: data.data.reporter, chooserTitle: '周报'),
            tooltip: '+1',
            child: Icon(Icons.send_sharp),
          ), // This trailing comma makes auto-formatting nicer for build methods.
        );
      },
    );
  }
}

class PullRefreshWithScrollView extends StatefulWidget {
  @override
  PullRefreshWithScrollViewState createState() {
    return new PullRefreshWithScrollViewState();
  }
}

class PullRefreshWithScrollViewState extends State<PullRefreshWithScrollView> {
  ScrollController _controller = new ScrollController();
  int _navBgColorAlpha = 0;

  @override
  void initState() {
    super.initState();
    _controller.addListener(() {
      setState(() {
        _navBgColorAlpha =
            (_controller.offset / 100 * 255).toInt().clamp(0, 255);
      });
    });
  }

  Future _onrefresh(AppData appData) async {
    if (appData.userPAT == '') return null;
    final stopwatch = Stopwatch()
      ..start();
    await appData.refresh();
    stopwatch.stop();
    return Future.delayed(
        Duration(milliseconds: max(0, 1000 - stopwatch.elapsedMilliseconds)));
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<AppData>(builder: (context, appdata, child) {
      var appBarMenu = <Widget>[
        IconButton(
          icon: Icon(
            Icons.next_week,
            color: Colors.white,
          ),
          onPressed: () => showInfoDialog(context),
        ),
        GestureDetector(
          onTap: () {
            showInfoDialog(context);
          },
          child: Text(
            " 周报生成",
            style: TextStyle(color: Colors.white, fontSize: 16.0),
          ),
        ),
        Spacer(),
      ];

      if (appdata.userIdentify != null) {
        appBarMenu.add(Padding(
          padding: const EdgeInsets.only(right: 16),
          child: GestureDetector(
            child: Text(
              appdata.userIdentify != null
                  ? appdata.userIdentify['DisplayName']
                  : '',
              style: TextStyle(color: Colors.white, fontSize: 16.0),
            ),
            onTap: () {
              goLogin(context);
            },
          ),
        ));
      }
      if (appdata.userIdentify == null)
        appBarMenu.add(IconButton(
          icon: Icon(
            Icons.account_circle_rounded,
            color: Colors.white,
            size: 28,
          ),
          onPressed: () => goLogin(context),
        ));
      return Material(
        child: Stack(
          fit: StackFit.expand,
          children: <Widget>[
            PullRefreshBox(
              onRefresh: () => _onrefresh(appdata),
              indicator: MyPullRefreshIndicator(
                style: TextStyle(color: Colors.white70),
                dragIndicator: Icon(
                  Icons.refresh,
                  color: Colors.white70,
                ),
                refreshIndicator: CircularProgressIndicator(
                  strokeWidth: 1.5,
                  valueColor: AlwaysStoppedAnimation<Color>(Colors.white70),
                ),
                //渐变效果
                decoration: BoxDecoration(
                    gradient: LinearGradient(
                      colors: [Colors.blue, Colors.blue[50]],
                      begin: Alignment.bottomCenter,
                      end: Alignment.topCenter,
                    )),
              ),
              child: Column(
                children: <Widget>[
                  Expanded(
                    child: SingleChildScrollView(
                      controller: _controller,
                      physics: AlwaysScrollableScrollPhysics(),
                      child: Column(children: <Widget>[
                        Container(
                            height: 190.0,
                            padding: EdgeInsets.only(top: 60.0),
                            color: Colors.blue,
                            alignment: Alignment.center,
                            child: Container(
                              alignment: Alignment.center,
                              padding: EdgeInsets.all(10),
                              width: 80,
                              height: 80,
                              decoration: BoxDecoration(
                                  borderRadius:
                                  new BorderRadius.all(Radius.circular(40)),
                                  color: Color(0xFF00bcd4)),
                              child: GestureDetector(
                                child: appdata.userIdentify != null
                                    ? Text(
                                  appdata.userIdentify['DisplayName']
                                      .substring(0, 1),
                                  style: TextStyle(
                                      color: Colors.white, fontSize: 40),
                                )
                                    : Text(
                                  '登录',
                                  style: TextStyle(
                                      color: Colors.white, fontSize: 20),
                                ),
                                onTap: () => goLogin(context),
                              ),
                            )),
                        ConstrainedBox(
                            constraints: BoxConstraints(
                                minHeight: 300,
                                minWidth: MediaQuery
                                    .of(context)
                                    .size
                                    .width),
                            child: Container(
                              child: Text(appdata.reporter,
                                  style: TextStyle(
                                      fontSize: 13,
                                      color: Colors.black54,
                                      fontWeight: FontWeight.w500)),
                              decoration: BoxDecoration(
                                  borderRadius: new BorderRadius.all(
                                      Radius.circular(10.0)),
                                  color: Color(0xffBBDEFB)),
                              padding: EdgeInsets.all(16),
                              margin: EdgeInsets.all(16),
                            )),
                      ]),
                    ),
                  ),
                ],
              ),
            ),
            // Navigation bar
            Positioned(
              left: .0,
              right: .0,
              child: Material(
                color: Colors.blue.withAlpha(_navBgColorAlpha),
                child: Padding(
                  padding: const EdgeInsets.only(top: 26.0),
                  child: SizedBox(
                    height: 56.0,
                    child: Row(children: appBarMenu),
                  ),
                ),
              ),
            ),
          ],
        ),
      );
    });
  }

  Future<Object> goLogin(BuildContext context) =>
      Navigator.pushNamed(context, "/login");

  Future showInfoDialog(BuildContext context) {
    return showDialog(
        context: context,
        child: new AlertDialog(
          title: new Text("云松周报生成器"),
          content: new Text("        Powered By Flutter"
              "\n\n                 Author: Xuyibo"),
        ));
  }
}

class MyPullRefreshIndicator extends PullRefreshIndicator {
  MyPullRefreshIndicator(
      {this.decoration, this.style, this.dragIndicator, this.refreshIndicator});

  final Decoration decoration;
  final TextStyle style;
  final Widget dragIndicator;
  final Widget refreshIndicator;

  @override
  Widget build(BuildContext context, PullRefreshIndicatorMode mode,
      double offset, ScrollDirection direction) {
    Widget child;
    if (mode == PullRefreshIndicatorMode.refresh) {
      child = Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          SizedBox(
            width: 20.0,
            height: 20.0,
            child: refreshIndicator ??
                CircularProgressIndicator(
                  strokeWidth: 2.0,
                ),
          ),
          Padding(
            padding: const EdgeInsets.only(left: 6.0),
            child: Text(
              "正在刷新...",
              style: style,
            ),
          )
        ],
      );
    } else {
      child = Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          TurnBox(
            turns: offset / 150.0,
            child: dragIndicator ?? Icon(Icons.refresh),
          ),
          Padding(
            padding: const EdgeInsets.only(left: 4.0),
            child: Text(
              offset > 80 ? "松开刷新" : "继续下拉",
              style: style,
            ),
          )
        ],
      );
    }
    return Container(
      alignment: Alignment.bottomCenter,
      decoration: decoration,
      padding: EdgeInsets.only(bottom: 20.0),
      height: 500.0,
      child: child,
    );
  }

  @override
  double get displacement => 80.0;

  @override
  double get height => 500.0;
}
